<?php

class MisCastHelper{
	private $mis_api;
	private $mis_pdes;
	private $error_msg;
	private $zh_lang;
	private $en_lang;
	private $relation_data;
	private $inserted_ids;
	private $updated_ids;
	private $new;
	private $link_list;
	private $change_logs=array();

	public function __construct(array $mis_pdes_data){
		$this->mis_api = new MisApi();
		$this->mis_pdes =  new mis_pdes();
		$this->zh_lang = language::getLanguageID(AC::LANGUAGE_ZH);
		$this->en_lang = language::getLanguageID(AC::LANGUAGE_EN);
		$mis_pdes_default = array(
			'type'     => '',    
			'mis_id'   => '',  
			'mis_eid'  => '', 
			'mis_pid'  => '', 
			'pdes_id'  => '', 
			'pdes_eid' => '',
			'pdes_pid' => '',
		);
		$this->relation_data = array_merge($mis_pdes_default,$mis_pdes_data);
		$this->relation_data['type'] = 'cast';
	}

	public function import(array $casts,$pid='',$type='others'){
		$error_msg = '';
		$import_ok = true;
		$this->inserted_ids = array();
		$this->updated_ids  = array();
		$this->link_list = array();
		$this->change_logs = array();
		#echo "\n============= Import Cast IDS\n";
		#print_r($casts);
		foreach($casts as $cast=>$role_id){
			$this->new = FALSE;
			$this->relation_data['mis_id'] = $cast;
			$cast_mis_data = $this->mis_api->getDataByApi('getCastDetails',array('KEY_ID'=>$cast));
			//new api function for cast details
			if($pid){
				$cast_details = $this->mis_api->getDataByApi('getPgmDefaultCastsDetails',array('KEY_ID'=>$pid));
				//merge with details
				$cast_mis_data->CASTS = $cast_details->CASTS;
				$cast_mis_data->CASTS_NICKNAME = $cast_details->CASTS_NICKNAME;
				$cast_mis_data->AGE = $cast_details->AGE;
				$cast_mis_data->OCCUPATION = $cast_details->OCCUPATION;
				$cast_mis_data->PERSONALITY = $cast_details->PERSONALITY;
				$cast_mis_data->PROFILE = $cast_details->PROFILE;
				$cast_mis_data->HISTORY = $cast_details->HISTORY;
			}
			$cast_mispdes_data = $this->mis_pdes->getRelation(array(
                'type' => 'cast',
                'mis_id' => $cast,
                'mis_pid' => $this->relation_data['mis_pid']));
			$is_insert = false;
			$log->type      = 'cast';
			if($cast_mispdes_data){
				$cast_mispdes_data = (object)$cast_mispdes_data[0];
				$updated_id = $this->replaceData($cast_mis_data,$cast_mispdes_data,$log,$role_id,$type);
			}else{
				$is_insert = true;
				//var_dump($role_id);
				$updated_id = $this->insertNew($cast_mis_data,$log,$role_id,$type);
			}

			if($updated_id){
				if($is_insert){
					//system will just update programme's main cast.
					if($role_id == 1 AND $type == 'programme'){
						$this->mis_pdes->updateRelation($this->relation_data);
					}else{
						$this->error_msg = '';
						continue;
					}
				}
			}else{
				$error_msg .= $this->error_msg."\n";
				$import_ok = false;
			}

			# write log
			$log->pdes_id   = $updated_id;
			$log->status    = $updated_id > 0;
			$log->message   = $this->error_msg;
            $log->modified_at = date('Y-m-d H:i:s');

			mis_log::update($log);

			$this->error_msg = ''; // flush for next cast
		}
		#echo "\n============= New Cast IDS\n";
		#print_r($this->inserted_ids);
		#echo "\n============= Replace Cast IDS\n";
		#print_r($this->updated_ids);
		$this->error_msg = $error_msg;
		return $import_ok;
	}

	public function getErrorMessage(){
		return $this->error_msg;
	}

	public function getInsertedIds(){
		return $this->inserted_ids;
	}

	public function getUpdatedIds(){
		return $this->updated_ids;
	}

	public function getLinkList()
	{
		return $this->link_list;
	}

	public function getChangeLogs(){
		return $this->change_logs;
	}

	private function replaceData($mis_obj,$mis_pdes_obj,$log,$role_id,$type){
		$cast = new cast();
		$cast = $cast->get($mis_pdes_obj->pdes_id);
		if(!$cast){
			$this->error_msg = "cast:{$mis_pdes_obj->pdes_id} not exists!";
			return false;
		}

		try{
			$new_cast_data          = MisMapping::getMapping('cast',$mis_obj);
			$new_cast_lang_data     = MisMapping::getMapping('cast-language',$mis_obj);
			$log->sync_data['Cast'] = MisMapping::formatLogData('cast',(array)$cast);
			$log->mis_data ['Cast'] = MisMapping::formatLogData('cast',(array)$new_cast_data);
			//$log->recover_sql[]     = MisMapping::getRecoverSql('cast',$cast);
			$cast = Model::diff($cast,$new_cast_data);

			//if(preg_match('/^[\w ]+$/',$new_cast_lang_data->real_first_name.$new_cast_lang_data->real_last_name)){
				//$lang = $this->en_lang;
			//}else{
				$lang = $this->zh_lang;
			//}

			$cast_language = Model::$dbo['r']->findInstance('cast_language',array($mis_pdes_obj->pdes_id,$lang));

			$log->sync_data['Cast Language'] = MisMapping::formatLogData('cast-language',(array)$cast_language);
			$log->mis_data ['Cast Language'] = MisMapping::formatLogData('cast-language',(array)$new_cast_lang_data);
			//$log->recover_sql[]              = MisMapping::getRecoverSql('cast-language',$cast_language);

			$cast_language = Model::diff($cast_language,$new_cast_lang_data);
		}catch(MISException $e){
			$this->error_msg = $e->getMessage();
			return false;
		}
        if($cast->gender  == '1') {
            $cast->gender  = 'M';
        }else if($cast->gender  == '2') {
            $cast->gender  = 'F';
        }else {
            $cast->gender  = '';
        }
		$cast->cast_role_id = $role_id;
		$cast->status = AC::STATUS_NEW;
		$cast->modified_at  = date('Y-m-d H:i:s');
		//var_dump($cast);
		//var_dump($cast_language);
		
		if ($type == 'programme') {
			$this->link_list[] = sprintf(AC::$mis_view_url, 'cast', $cast->id);
			if ($this->new === TRUE) {
				Model::$dbo['w']->save($cast);
				Model::$dbo['w']->save($cast_language);

				# change_log
				$change_data = ChangeLogTools::getEpisodeIdsByCastId($cast->id);
				$change_data['is_active']  = 1;
				$change_data['is_publish'] = 0;
				$change_data['type'] = 'cast';
				$change_data['keys'] = array('id'=>$cast->id);
				$this->change_logs[] = $change_data;
				$change_data['type'] = 'cast-language';
				$change_data['keys'] = array('cast_id'=>$cast->id,'language_id'=>$cast_language->language_id);
				$this->change_logs[] = $change_data;
			}
		};

		$this->updated_ids[$cast->cast_role_id][] = array(
			'cast_id'=>$mis_pdes_obj->pdes_id,
			'name_type'=>1,
			'last_name'=>$cast_language->real_last_name,
			'first_name'=>$cast_language->real_first_name,
			'alphabet'=> ($lang==$this->en_lang ? 0 : 1 )
		);
		//var_dump($cast->id);
		
		return $cast->id;
	}

	private function insertNew($mis_obj,$log,$role_id,$type){
		try{
			$mis_cast_data                   = MisMapping::getMapping('cast',$mis_obj);
			$mis_cast_lang_data              = MisMapping::getMapping('cast-language',$mis_obj);
			$log->mis_data ['Cast']          = MisMapping::formatLogData('cast',(array)$mis_cast_data);
			$log->mis_data ['Cast Language'] = MisMapping::formatLogData('cast-language',(array)$mis_cast_lang_data);
		}catch(MISException $e){
			$this->error_msg = $e->getMessage();
			return false;
		}

		$objs = array();
		$objs['cast'] = new cast();
		#$objs['cast'] = Model::diff($objs['cast'],$mis_cast_data);
		if($role_id == 1){
			$objs['cast']->set( $mis_cast_data );
			$objs['cast']->programme_id = $this->relation_data['pdes_pid'];
			$objs['cast']->cast_role_id = $role_id;
        	if($objs['cast']->gender == '1') {
        	    $objs['cast']->gender = 'M';
        	}else if($objs['cast']->gender == '2') {
           		$objs['cast']->gender = 'F';
       		}else {
            	$objs['cast']->gender = '';
        	}
			#print_r($objs['cast']);

			$objs['cast-language'] = new cast_language();
			$objs['cast-language']->set( $mis_cast_lang_data );

			//if(preg_match('/^[\w ]+$/',$objs['cast-language']->real_first_name.$objs['cast-language']->real_last_name)){
				//$objs['cast-language']->language_id = $this->en_lang;
			//}else{
			$objs['cast-language']->language_id = $this->zh_lang;
			//}

		#  Save 
			$objs['cast']->status      = AC::STATUS_NEW;
			$objs['cast']->modified_at = date('Y-m-d H:i:s');
			$objs['cast']->created_at  = date('Y-m-d H:i:s');

			if ($type == 'programme') {
				$new_cast_id = Model::$dbo['w']->save($objs['cast']);
				$objs['cast-language']->cast_id = $new_cast_id;
				Model::$dbo['w']->save($objs['cast-language']);
				#print_r($objs['cast-language']);
				$this->relation_data['pdes_id'] = $new_cast_id;

				# change_log
				$this->change_logs[] = array(
					'type'=>'cast',
					'keys'=>array('id'=>$new_cast_id),
					'is_active'=>1,
					'is_publish'=>0,
					'programme_id'=>$objs['cast']->programme_id
				);
				$this->change_logs[] = array(
					'type'=>'cast',
					'keys'=>array('cast_id'=>$new_cast_id,'language_id'=>$this->zh_lang),
					'is_active'=>1,
					'is_publish'=>0,
					'programme_id'=>$objs['cast']->programme_id
				);
			} else {
				$new_cast_id = '';
			}

			$this->inserted_ids[$role_id][] = array(
				//'cast_id'=>$new_cast_id,
				'cast_id' => $new_cast_id,
				'name_type'=>1,
				'last_name'=>$objs['cast-language']->real_last_name,
				'first_name'=>$objs['cast-language']->real_first_name,
				'alphabet'=>($objs['cast-language']->language_id == $this->en_lang ? 0 : 1)
			);
			return $new_cast_id;
		}else{
			$new_cast_id = '';
			$this->inserted_ids[$role_id][] = array(
			//'cast_id'=>$new_cast_id,
			'cast_id'=>$new_cast_id,
			'name_type'=>1,
			'last_name'=>$mis_cast_lang_data->real_last_name,
			'first_name'=>$mis_cast_lang_data->real_first_name,
			'alphabet'=>1,
			);
			return TRUE;
		}
	}
}
